package nsn.excel.read.readmodel;

import nsn.excel.read.ExcelReadBase;
import nsn.excel.entity.ExcelPointer;
import org.apache.commons.collections4.map.LinkedMap;
import org.apache.poi.ss.usermodel.Sheet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

/**
 * Excel 流程控制
 */
public abstract class AbstractModelExcelRead extends ExcelReadBase implements ModelExcelRead {
    //配置文件匹配
    private final static Pattern CONFIGMATCHER = Pattern.compile("#\\{(.*?)}");
    //内容匹配
    private final static Pattern CONTENTMATCHER = Pattern.compile("\\$\\{(.*?)}");
    // 日志打印类
    private static Logger logger = Logger.getLogger(AbstractModelExcelRead.class.getName());


    /**
     * 指针定位 为解析数据判断出正确的行数
     *
     * @param excelPointer excle解析指针
     * @param source       模板源数据
     * @param target       目标源数据
     * @return
     */
    public abstract ExcelPointer getPointer(ExcelPointer excelPointer, String[] configArry, List<Map<String, Object>> source, List<Map<String, Object>> target);


    @Override
    public Map<String, Object> modelParseData(String modelPath, String filePath) {
            List<Map<String, Object>> modelData = this.parse(modelPath, 0);
            List<Map<String, Object>> fileData = this.parse(filePath, 0);
            return parseData(modelData, fileData);
    }

    @Override
    public Map<String, Object> modelParseData(InputStream modelStream, InputStream fileStream, String suffix) {
        List<Map<String, Object>> modelData = parse(modelStream, suffix, 0);
        List<Map<String, Object>> fileData = parse(fileStream, suffix, 0);
        return parseData(modelData, fileData);

    }

    @Override
    public Map<String, Object> modelParseData(List<Map<String, Object>> modelData, InputStream fileStream, String suffix) {
        List<Map<String, Object>> fileData = parse(fileStream, suffix, 0);
        return parseData(modelData,fileData);
    }

    /**
     * 解析数据
     *
     * @param soucre excle模板数据
     * @param target 需要解析的excel模板
     * @return target
     */
    public Map parseData(List<Map<String, Object>> soucre, List<Map<String, Object>> target) {

        ExcelPointer excelPointer = new ExcelPointer();
        Map<String, Object> resultMap = new HashMap<>();
        String configKey = null;
        try{
        //遍历数据解析
        for (int i = 0; i < soucre.size(); i++) {
            excelPointer.setIndex(i);


            //1.找到这个模板进行解析 首先第一次确定配置行的所在列
            if (configKey == null && CONFIGMATCHER.matcher(soucre.get(i).toString()).find()) {
                Map<String, Object> map = soucre.get(i);
                for (String key : map.keySet()) {
                    if (map.get(key) != null && CONFIGMATCHER.matcher(map.get(key).toString()).find()) {
                        configKey = key;
                    }
                }
            }
            excelPointer.setConfigKey(configKey);
            //判断配置行是否操作
            if (soucre.get(i).get(configKey) != null && CONFIGMATCHER.matcher(soucre.get(i).get(configKey).toString()).find()) {
                String config = soucre.get(i).get(configKey).toString();
                String[] configArry = config.substring(2, config.length() - 1).split(":");

                //2.根据配置行 来移动指针  锁定解析的数据
                getPointer(excelPointer, configArry, soucre, target);
                //配置文件少于3 说明是定位的
                if(configArry.length<3)continue;
                //3.解析数据  解析数据
                analyticalData(excelPointer, configArry, soucre, target, resultMap);
            }
        }
        }catch (Exception e){
            logger.log(Level.ALL,"文件解析异常 请检查适配器是否正常");
            e.printStackTrace();
        }
        return resultMap;
    }


    /**
     * 数据存储
     *
     * @param excelPointer
     * @param configArry
     * @param source
     * @param target
     * @param resultMap
     * @return
     */
    private Map analyticalData(ExcelPointer excelPointer, String[] configArry, List<Map<String, Object>> source, List<Map<String, Object>> target, Map resultMap) {
        if(excelPointer.getStart()>excelPointer.getEnd()){
            return resultMap;
        }
        String type = configArry[1];
        if ("map".equalsIgnoreCase(type)) {
            for (int i = excelPointer.getStart(); i <= excelPointer.getEnd(); i++) {
                Map map = sourceToTarget(source.get(excelPointer.getIndex()), target.get(i));
                //更新
                if (resultMap.containsKey(configArry[2])) {
                    Map m = (Map) resultMap.get(configArry[2]);
                    m.putAll(map);
                    resultMap.put(configArry[2], m);
                }
                //插入
                else {
                    resultMap.put(configArry[2], map);
                }
            }
        }
        if ("list".equalsIgnoreCase(type)) {
            List<Map> list = new LinkedList<>();
            for (int i = excelPointer.getStart(); i <= excelPointer.getEnd(); i++) {
                Map map = sourceToTarget(source.get(excelPointer.getIndex()), target.get(i));
                list.add(map);
            }
            resultMap.put(configArry[2], list);
        }
        return resultMap;
    }

    /**
     * 数据解析
     *
     * @param sourceMap 模板Excel数据
     * @param targetMap 数据源模板
     * @return
     */
    private Map<String, Object> sourceToTarget(Map<String, Object> sourceMap, Map<String, Object> targetMap) {
        Map<String, Object> dataMap = new LinkedMap();
        for (String key : sourceMap.keySet()) {
            if (sourceMap.get(key) != null && CONTENTMATCHER.matcher(sourceMap.get(key).toString()).find()) {
                String sourceValue = sourceMap.get(key).toString();
                String targetValue = targetMap.get(key)==null?null:targetMap.get(key).toString();
                Map<String, Object> cells = this.split(sourceValue, targetValue);
                for (String cellKey : cells.keySet()) {
                    mapSaveOrUpdate(cellKey.split("\\."), dataMap, cells.get(cellKey));
                }
            }
        }
        return dataMap;
    }

    /**
     * 插入更新
     * @param config
     * @param dataMap
     * @param value
     * @return
     */
    private void mapSaveOrUpdate(String[] config, Map<String, Object> dataMap, Object value) {
        //更新
        if (dataMap.containsKey(config[0])) {
            Map<String, Object> map = (Map<String, Object>) dataMap.get(config[0]);
            map.put(config[1], value);
        } else {
            //插入
            if (config.length <= 1) {
                dataMap.put(config[0], value);
            } else {
                Map<String, Object> map = new HashMap<>();
                map.put(config[1], value);
                dataMap.put(config[0], map);
            }
        }
    }


}
